﻿/*

  Copyright (C) 2013 xubinbin 徐彬彬 (Beijing China)

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

  
  filename: main.c 
  version : v1.1.0
  time    : 2013/08/02 16:20 
  author  : xubinbin ( xubbwd@gmail.com )
  code URL: http://code.google.com/p/tsdemux/

*/

#include "fa_parseopt.h"
#include "fa_ps2es.h"


int main(int argc,char * argv[])
{

    int ret = 0;
    unsigned int es_data_length = 0;
    
	unsigned char ps_buffer[PS_INPUT_SIZE];
	unsigned char es_buffer[PS_MAX_BUF];

	FILE * fp_sourcefile = NULL;
	FILE * fp_destfile = NULL;


    ret = fa_parseopt(argc, argv);
    if(ret) return -1;

	if ((fp_sourcefile = fopen(opt_inputfile, "rb")) == NULL) {
		printf("input file can not be opened;\n");
		return 0;
    }
	if(strlen(opt_outputfile) > 0) {
		if ((fp_destfile = fopen(opt_outputfile, "wb")) == NULL) {
			printf("output file can not be opened\n");
			return 0;
		}
	}
    
	psdemux *psdemux_info = NULL;
    psdemux_info = (psdemux *)malloc(sizeof(psdemux));
    memset(psdemux_info,0,sizeof(psdemux));
	ret = psdemux_init(psdemux_info);
	if(ret < 0){
		printf("psdemux init error\n");
		return -1;
	}

    while(1)
    {
        memset(ps_buffer,0,PS_INPUT_SIZE);
        if(fread(ps_buffer,PS_INPUT_SIZE,1,fp_sourcefile) != 1) {
        	printf("read ps_buffer over !\n");
        	break;
        }
        psdemux_info->readin_data_flag = 0;
        while( psdemux_get_es_process(psdemux_info,ps_buffer,PS_INPUT_SIZE,es_buffer,&es_data_length) > 0 )
        {
            if(strlen(opt_outputfile) > 0)
            {
                if(es_data_length > 0)
                {
                    //printf("es_data_length = %d\n",es_data_length);
                    ret = fwrite(es_buffer,es_data_length,1,fp_destfile);
                    if(ret != 1)
                    {
                        printf("fwrite file error!\n");
                    }
                    es_data_length = 0;
                    memset(es_buffer,0,PS_MAX_BUF);
                }
                
            }
        }
    }

    psdemux_deinit(psdemux_info);
    
    fclose(fp_sourcefile);
    if(strlen(opt_outputfile) > 0) {
    	fclose(fp_destfile);
    }

    printf("Done.\n");

    return 0;
}

